package com.xuzao.developer.controller;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.xuzao.developer.annotation.MethodAnnotation;
import com.xuzao.developer.annotation.ModuleAnnotation;
import com.xuzao.developer.base.model.AddressServer;
import com.xuzao.developer.base.model.GridFieldSys;
import com.xuzao.developer.base.model.GridTable;
import com.xuzao.developer.dao.GridFieldSysDao;
import com.xuzao.developer.dao.GridTableDao;
import com.xuzao.developer.dingding.RebootUtil;
import com.xuzao.developer.dto.AddressServerDTO;
import com.xuzao.developer.service.AddressServerService;
import com.xuzao.developer.tools.entity.Pager;
import com.xuzao.developer.utils.BJUIMap;
import com.xuzao.developer.utils.DateUtil;
import com.xuzao.developer.utils.JasyptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xuzao
 * @description
 * @date 2019-09-03 17:32:07
 **/
@Controller
@ModuleAnnotation(name = "数据库")
@RequestMapping("/addressServer/")
public class AddressServerController {

    @Resource
    private AddressServerService addressServerService;
    @Resource
    private GridTableDao gridTableDao;
    @Resource
    private GridFieldSysDao gridFieldSysDao;

    @RequestMapping("queryList")
    public String queryList(AddressServerDTO dto, Pager pager, Model model) {

        PageInfo<AddressServer> pageInfo = addressServerService.list(dto, pager);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("bo", dto);
        return "/address_server/address_server_list";
    }

    @MethodAnnotation(name = "新增")
    @RequestMapping("add")
    public String add(Model model) {
        model.addAttribute("bo", new AddressServer());
        return "/address_server/address_server_add";
    }

    @MethodAnnotation(name = "修改")
    @RequestMapping("update")
    public String update(Model model, Long id) {
        model.addAttribute("bo", addressServerService.get(id));
        return "/address_server/address_server_update";
    }

    @MethodAnnotation(name = "保存")
    @RequestMapping("save")
    @ResponseBody
    public BJUIMap save(AddressServerDTO dto) {
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("addressServer");
        map.setCloseCurrent(BJUIMap.CALLBACK_CLOSE);
        map.setStatusCode(BJUIMap.CODE_OK);
        if (StringUtils.isNotBlank(dto.getFlag())) {
            addressServerService.insert(dto);
        } else {
            addressServerService.update(dto);
        }
        return map;
    }

    @MethodAnnotation(name = "删除")
    @RequestMapping("del")
    @ResponseBody
    public BJUIMap del(Long id) {
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("addressServer");
        map.setStatusCode(BJUIMap.CODE_OK);
        addressServerService.del(id);
        return map;
    }

    @MethodAnnotation(name = "同步")
    @RequestMapping("publish")
    @ResponseBody
    public BJUIMap publish(AddressServerDTO dto) {
        BJUIMap map = new BJUIMap();
        map.setMessage("操作成功");
        map.setTabid("addressServer");
        map.setStatusCode(BJUIMap.CODE_OK);

        new Thread(() -> {
            String result = "SUCCESS";
            String es = null;
            AddressServer addressServer = addressServerService.get(dto.getId());
            List<GridTable> gridTables = gridTableDao.list(null,null).getList();
            List<GridFieldSys> gridFieldSysList = gridFieldSysDao.selectListAll();
            Map<String,Long> gridTableMap = Maps.newHashMap();

            String JDBC_DRIVER = "com.mysql.jdbc.Driver";
            String DB_URL = "jdbc:mysql://" + addressServer.getAddressId() + ":" + addressServer.getAddressPort() + "/basics?useUnicode=true&characterEncoding=UTF8&useSSL=false&jdbcCompliantTruncation=false";
            Connection conn = null;
            Statement statement = null;
            try {
                // 注册 JDBC 驱动
                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(DB_URL, addressServer.getAddressUser(), JasyptUtil.decrypt(addressServer.getAddressPassword()));
                statement = conn.createStatement();


                statement.execute("TRUNCATE TABLE grid_table");
                statement.execute("TRUNCATE TABLE grid_field_sys");

                if (!gridTables.isEmpty()) {

                    for (int i = 0; i < gridTables.size(); i++) {
                        StringBuilder sb = new StringBuilder("insert into grid_table(`id`,`grid_name`,`party_id`,`warehouse_id`," +
                                "`operator_id`,`creater_name`,`modifer_name`,`update_version`,`gmt_create`,`gmt_modified`,`is_deleted`) values ");
                        GridTable item = gridTables.get(i);
                        if (item.getGmtModified() == null) {
                            item.setGmtModified(new Date());
                        }
                        if (item.getGmtCreate() == null) {
                            item.setGmtCreate(new Date());
                        }
                        sb.append("(").append(item.getId()).append(",'").append(item.getGridName()).append("','").append(item.getPartyId()).append("','").append(item.getWarehouseId()).append("','").append(item.getOperatorId())
                                .append("','").append(item.getCreaterName()).append("','").append(item.getModiferName()).append("','").append(item.getUpdateVersion()).append("','").append(DateUtil.formatFully(item.getGmtCreate())).append("','")
                                .append(DateUtil.formatFully(item.getGmtModified())).append("',").append(item.getIsDeleted()).append(")");

                        gridTableMap.put(item.getId().toString(),1L);
                        statement.executeUpdate(sb.toString());
                    }

                }

                if (!gridFieldSysList.isEmpty()) {

                    for (int i = 0; i < gridFieldSysList.size(); i++) {
                        GridFieldSys item = gridFieldSysList.get(i);
                        if (null == gridTableMap.get(item.getGridId())){
                            continue;
                        }
                        StringBuilder sb = new StringBuilder("insert into grid_field_sys(`id`,`grid_id`,`grid_name`,`grid_field_id`,`templet`,`party_id`,`warehouse_id`,`operator_id`,`display_order`,`field_name`,`field_caption`,`field_default_value`,`field_can_used`,`field_type`,`width`," +
                                "`print_flag`,`dic_no`,`creater_name`,`modifer_name`,`gmt_create`,`gmt_modified`,`is_deleted`) values");

                        if (item.getGmtModified() == null) {
                            item.setGmtModified(new Date());
                        }
                        if (item.getGmtCreate() == null) {
                            item.setGmtCreate(new Date());
                        }
                        sb.append("(").append(item.getId()).append(",'").append(item.getGridId()).append("','").append(item.getGridName()).append("','").append(item.getGridFieldId()).append("','").append(item.getTemplet())
                                .append("','").append(item.getPartyId()).append("','").append(item.getWarehouseId()).append("','").append(item.getOperatorId()).append("','").append(item.getDisplayOrder()).append("','")
                                .append(item.getFieldName()).append("','").append(item.getFieldCaption()).append("','").append(item.getFieldDefaultValue()).append("','").append(item.getFieldCanUsed()).append("','")
                                .append(item.getFieldType()).append("','").append(item.getWidth()).append("','").append(item.getPrintFlag())
                                .append("','").append(item.getDicNo()).append("','").append(item.getCreaterName()).append("','").append(item.getModiferName()).append("','")
                                .append(DateUtil.formatFully(item.getGmtCreate())).append("','").append(DateUtil.formatFully(item.getGmtModified())).append("',").append(item.getIsDeleted()).append(")");
                        System.out.println(sb.toString());
                        statement.executeUpdate(sb.toString());
                    }

                }


            } catch (Exception e) {
                e.printStackTrace();
                es = e.getCause().toString();
                result = "FAIL";
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                    if (statement != null) {
                        statement.close();
                    }
                } catch (SQLException se) {
                    se.printStackTrace();
                }
                String msg = "表头数据同步完成，数据库【" + addressServer.getAddressName() + "】,结果【" + result + "】,INFO ==>" + es;
                RebootUtil.setMessage(false, msg, null);
            }

        }).start();


        return map;
    }


}